package com.ruoyi.web.controller.system;

import com.google.common.collect.Lists;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.file.FileUtil;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.SysFile;
import com.ruoyi.system.service.ISysFileService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 附件Controller
 * 
 * @author ruoyi
 * @date 2022-09-04
 */
@RestController
@RequestMapping("/system/file")
public class SysFileController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);


    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public AjaxResult upload(MultipartFile[] file) {
        try {
            // 上传并返回访问地址
            List<SysFile> uploadFile = sysFileService.upload(file);
            return AjaxResult.success(uploadFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("upload/img")
    public AjaxResult uploadImg(MultipartFile file, @RequestParam int width, @RequestParam int height) {
        final String attachSuffix = FileUtil.getFileExtension(file.getOriginalFilename());
        if(!Lists.newArrayList(MimeTypeUtils.IMAGE_EXTENSION).contains(attachSuffix)) {
            throw new ServiceException("该文件不是图片！");
        }
        try {
            // 上传并返回访问地址
            SysFile uploadFile = sysFileService.uploadImg(file, width, height);
            return AjaxResult.success(uploadFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 文件删除请求
     */
    @PostMapping("delete")
    public AjaxResult delete(@RequestParam Long fileId) {
        try {
            sysFileService.delete(fileId);
            return AjaxResult.success("删除成功!");
        } catch (Exception e) {
            log.error("删除文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 资源下载
     */
    @GetMapping("/download")
    @ApiOperation("资源下载")
    public void download(@RequestParam String fileKey, HttpServletResponse response) {
        SysFile sysFile = sysFileService.getById(fileKey);
        sysFileService.download(sysFile.getPath(), sysFile.getFileName(), false, response);
    }
}
